<?php
// +---------------------------------------------------------------------+
// | OneBase    | [ WE CAN DO IT JUST THINK ]                            |
// +---------------------------------------------------------------------+
// | Licensed   | http://www.apache.org/licenses/LICENSE-2.0 )           |
// +---------------------------------------------------------------------+
// | Author     | 王勇程 <laughskydragon@qq.com>                         |
// +---------------------------------------------------------------------+
// | Repository | https://gitee.com/Bigotry/OneBase                      |
// +---------------------------------------------------------------------+

namespace app\common\model;

/**
 * 商品模型
 */
class Product extends ModelBase
{
    // 商品状态常量
    const PRODUCT_STATUS_OFFLINE = 0; // 下架
    const PRODUCT_STATUS_ONLINE = 1;  // 上架

    // 保持旧常量以兼容现有代码
    const STATUS_OFFLINE = 0; // 下架
    const STATUS_ONLINE = 1;  // 上架
    
    public $base = [
        'categories' => [
            'tobacco' => '烟草',
            'alcohol' => '酒类',
            'tea' => '茶叶'
        ],
    ];

    protected $append = ['change_amount', 'change_rate'];

    /**
     * 获取批发价格
     */
    public function getWholesalePriceAttr($value)
    {
        return floatval($value);
    }
    
    /**
     * 获取指导价格
     */
    public function getGuidePriceAttr($value)
    {
        return floatval($value);
    }
    
    /**
     * 获取市场价格
     */
    public function getMarketPriceAttr($value)
    {
        return floatval($value);
    }
    
    /**
     * 获取价格变动金额
     */
    public function getChangeAmountAttr($value, $data)
    {
        $yesterdayPrice = $this->_getYesterdayPrice($data['id']);
        $marketPrice = floatval($data['market_price']);
        
        if ($yesterdayPrice > 0) {
            return $marketPrice - $yesterdayPrice;
        }
        return null; // 昨日价格为0时，变化金额为空
    }

    /**
     * 获取价格变动率（保留1位小数）
     */
    public function getChangeRateAttr($value, $data)
    {
        $yesterdayPrice = $this->_getYesterdayPrice($data['id']);
        $marketPrice = floatval($data['market_price']);

        if ($yesterdayPrice > 0) {
            $changeAmount = $marketPrice - $yesterdayPrice;
            $changeRate = ($changeAmount / $yesterdayPrice) * 100;
            return round($changeRate, 1); // 四舍五入保留1位小数
        }
        return null; // 昨日价格为0时，变化率为空
    }
    
    /**
     * 获取昨日价格
     * @param $value
     * @param $data
     * @return float|null
     */
    public function getYesterdayPriceAttr($value, $data)
    {
        return $this->_getYesterdayPrice($data['id']);
    }
    
    private $_cachedYesterdayPrice = [];

    /**
     * 获取指定商品的昨日价格 (私有方法)
     * @param int $productId 商品ID
     * @return float 昨日价格，如果不存在则返回0
     */
    private function _getYesterdayPrice(int $productId): float
    {
        // 检查是否已缓存
        if (isset($this->_cachedYesterdayPrice[$productId])) {
            return $this->_cachedYesterdayPrice[$productId];
        }

        // 确保 modelPriceHistory 已被初始化
        if (!isset($this->modelPriceHistory)) {
            $this->modelPriceHistory = new \app\common\model\PriceHistory();
        }

        $yesterdayDate = date('Y-m-d', strtotime('-1 day'));

        // 尝试获取昨日的价格记录
        $yesterdayPriceRecord = $this->modelPriceHistory->getInfo(
            [
                'product_id' => $productId,
                'price_date' => ['<=', $yesterdayDate]
            ],
            true,
            'price_date desc'
        );

        $price = $yesterdayPriceRecord ? floatval($yesterdayPriceRecord['price']) : floatval($this->getData('market_price'));

        // 缓存结果
        $this->_cachedYesterdayPrice[$productId] = $price;

        return $price;
    }
    
    /**
     * 获取商品主图
     */
    public function getCoverImageAttr($value = null, $data = [])
    {
        return get_picture_url($data['cover_id']);
    }
    
    /**
     * 获取商品多图片
     */
    public function getImagesAttr($value = null, $data = [])
    {
        if (empty($data['img_ids'])) {
            return [];
        }
        
        $imgIds = explode(',', $data['img_ids']);

        return $this->modelPicture->getList(['id' => ['in', $imgIds]], '*', 'id', false);
    }

    /**
     * 获取商品状态文本
     */
    public function getProductStatusTextAttr($value = null, $data = [])
    {
        $product_status = $data['product_status'] ?? 0;
        return $product_status == self::PRODUCT_STATUS_ONLINE ? '上架' : '下架';
    }
    
    /**
     * 获取分类文本
     */
    public function getCategoryTextAttr($value = null, $data = [])
    {
        // 优先使用新的分类ID字段
        if (!empty($data['category_id'])) {
            $categoryModel = new \app\common\model\Category();
            $category = $categoryModel->getInfo(['id' => $data['category_id']], 'name');
            return $category ? $category['name'] : '未知分类';
        }
        
        // 兼容旧的字符串分类字段
        $categories = $this->base['categories'];
        return $categories[$data['category']] ?? '未知';
    }
    
    /**
     * 获取分类信息
     */
    public function getCategoryInfoAttr($value = null, $data = [])
    {
        if (empty($data['category_id'])) {
            return null;
        }
        
        $categoryModel = new \app\common\model\Category();
        return $categoryModel->getInfo(['id' => $data['category_id']]);
    }
    
    /**
     * 获取分类路径
     */
    public function getCategoryPathAttr($value = null, $data = [])
    {
        if (empty($data['category_id'])) {
            return [];
        }
        
        $categoryModel = new \app\common\model\Category();
        $category = $categoryModel->getInfo(['id' => $data['category_id']]);
        
        if (!$category) {
            return [];
        }
        
        return $categoryModel->getCategoryPathArray($category['path']);
    }
    

    

}